import _ from 'underscore'
import dispatcher from 'lib/dispatcher'
import {Scope} from 'lib/scopeFactory'
import {list} from '../apis/urlGroup'
import basicInfo from '../apis/basicInfo'
export default class MainScope extends Scope {
  constructor(){
    super();
    this.$state = {
      grid:{
        loading:true
      },
      domains:[]
    };
    this.listApi = list()
    this.domainApi = basicInfo({
      urlName:'url',
      parentId:0
    })
  }
  fetch(){
    this.listApi.fetch().then((data,params) => {
      this.$state.grid = {
        data:data
      }
    },(err) => {
      this.$state.grid = {
        error:err
      }
    },(params) => {
      this.$state.grid = {
        loading:true
      }
      this.emit()
    }).always(() => this.emit())
  }
  $update_urlgroup(payload){
    if(this.$state.grid.data){
      var finded = _(this.$state.grid.data).find((a) => a.id === payload.urlGroup.id)
      if(finded){
        _.extend(finded,payload.urlGroup)
      }else{
        this.$state.grid.data.push(payload.urlGroup)
      }
      this.emit()
    }
  }
  $delete_urlgroup(payload){
    if(this.$state.grid.data){
      this.$state.grid.data = _(this.$state.grid.data).filter((a) => a.id === payload.id)
      this.emit()
    }
  }
  $load(){
    this.fetch()
    this.domainApi.fetch().then((data,params) => {
      this.$state.domains = data.result
      this.emit()
    })
  }
}
